package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.HasPermi;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.dao.SysDept;
import com.ruoyi.system.domain.query.SysDeptQo;
import com.ruoyi.system.domain.wrapper.query.SysDeptWrapperQ;
import com.ruoyi.system.domain.wrapper.view.SysDeptWrapperV;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 部门Controller
 *
 * @author 尹国春
 * @date 2022-07-25
 */
@Api(value = "部门", tags = {"部门"})
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController

{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 部门分页查询
     */
    @ApiOperation(value="部门分页查询",notes="分页参数：pageNum,pageSize,orderByColumn(数据库字段名称),isAsc(asc|desc)")
    @HasPermi("system:dept:list")
    @GetMapping("/list")
    public AjaxResult<List<SysDept>> list(SysDeptQo sysDept)
    {
        List<SysDept> list=deptService.list(SysDeptWrapperQ.getQueryWrapper(sysDept));
        return AjaxResult.success(list);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @HasPermi("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) String deptId)
    {
        List<SysDept> list=deptService.list(null);
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().equals(deptId)
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId))
            {
                it.remove();
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取部门详细信息
     */
    @ApiOperation("部门信息")
    @HasPermi("system:dept:list")
    @GetMapping(value = "/get/{deptId}")
    public AjaxResult getInfo(@PathVariable("deptId") String deptId)
    {
        SysDept entity=deptService.getById(deptId);
        return AjaxResult.success(SysDeptWrapperV.build().entityVO(entity));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.list(SysDeptWrapperQ.getQueryWrapper(dept));
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 新增部门
     */
    @HasPermi("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        return toAjax(deptService.insert(dept));
    }

    /**
     * 修改部门
     */
    @HasPermi("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        String deptId = dept.getDeptId();
        if (dept.getParentId().equals(deptId)){
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        return toAjax(deptService.updateById(dept));
    }

    /**
     * 删除部门
     */
    @HasPermi("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{deptId}")
    public AjaxResult remove(@PathVariable String deptId)
    {
        if (deptService.hasChildByDeptId(deptId)){
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)){
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.removeById(deptId));
    }
}
